package com.jushu.storbox.adapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.actions.ThumbnailAction;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.operation.group.FileItemMoreOperation;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.PopupMenuWindow;

public class TeamFileDisplayAdapter extends ListDisplayResolveAdapter<FileFolderInfo, FileItemMoreOperation<FileFolderInfo>> {

	public static final String TAG = TeamFileDisplayAdapter.class.getSimpleName();
	private LayoutInflater mInflater;
	Context context;
	private PopupMenuWindow popWindow;

	public TeamFileDisplayAdapter(Context context, List<FileFolderInfo> datasList) {
		super(datasList);
		mInflater = LayoutInflater.from(context);
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if(convertView == null) {
			holder = new ViewHolder(mInflater, parent);
			convertView = holder.baseView;
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		holder.bindingData(position, getItem(position));
		
		return convertView;
	}
	
	public PopupMenuWindow getPopWindow() {
		return popWindow;
	}

	public void setPopWindow(PopupMenuWindow popWindow) {
		this.popWindow = popWindow;
	}

	public class ViewHolder {
		//ui view
		View baseView;
		ImageView mItemIcon;
		TextView mItemName;
		TextView mItemDate;
		TextView mItemSize;
		CheckBox mItemCheckBox;
		View mItemMore;
		
		//data index
		int mIndex;
		//data
		FileFolderInfo mInfo;
		String iconPath;
		
		public FileFolderInfo getmInfo() {
			return mInfo;
		}

		public ViewHolder(LayoutInflater mInflater, ViewGroup parent) {
			
			//init view
			baseView = mInflater.inflate(R.layout.new_item_filelist, parent, false);
			mItemIcon = (ImageView) baseView.findViewById(R.id.item_type_img);
			mItemName = (TextView) baseView.findViewById(R.id.item_name_text);
			mItemDate = (TextView) baseView.findViewById(R.id.item_date_text);
			mItemSize = (TextView) baseView.findViewById(R.id.item_filelist_file_size);
			mItemCheckBox = (CheckBox) baseView.findViewById(R.id.chx_file_item);
			mItemMore = baseView.findViewById(R.id.item_more_ll);
			
			//show more operation window
			mItemMore.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					int[] loction = new int[2];
					view.getLocationOnScreen(loction);
	                int showMoreMenuY = loction[1];
	                if(popWindow != null) {
	    				popWindow.showAtLocation(baseView, Gravity.TOP, 0, showMoreMenuY
	    	                    + (view.getHeight() / 2 + 20));
	    			}
	                FileItemMoreOperation<FileFolderInfo> currentOperation = getOperation();
	                if(currentOperation != null) {
	                	currentOperation.onItemMore(mIndex, mInfo);
	                }
				}
			});
		}
		
		public void bindingData(int index, FileFolderInfo info) {
			mIndex = index;
			mInfo = info;
			//bindding data
			mItemIcon.setImageResource(getTypeImgeID());
			mItemName.setText(info.getName());
			if(mInfo.getIsFile() == FileType.File.value()) {
				mItemDate.setVisibility(View.VISIBLE);
				mItemDate.setText(formatDate());
				mItemSize.setVisibility(View.VISIBLE);
				mItemSize.setText(PublicTools.changeBKM(String.valueOf(mInfo.getSize())));
			} else {
				mItemDate.setVisibility(View.VISIBLE);
				mItemDate.setText(formatDate());
				mItemSize.setVisibility(View.INVISIBLE);
			}
			if(isMultiMode()){
				mItemCheckBox.setVisibility(View.VISIBLE);
			}else{
				mItemCheckBox.setVisibility(View.GONE);
			}
//			if(isSelectAllMode()){
//				mItemCheckBox.setChecked(true);
//			}else{
				mItemCheckBox.setChecked(false);
//			}
			
		}
		
		@SuppressLint("SimpleDateFormat")
		private String formatDate() {
			SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
            return timeDateFormat.format(mInfo.getModifiedAt());
		}
		
		private int getTypeImgeID() {
			// LogUtil.i(TAG, "getTypeImgeID...");
			int typeImgResId = R.mipmap.default_file_icon;
			if(mInfo.getIsFile() == FileType.File.value()) {
				if (PublicTools.isFileType(mInfo.getName(),
						Constant.WORD_TYPE)) {
					typeImgResId = R.mipmap.doc;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.PPT_TYPE)) {
					typeImgResId = R.mipmap.ppt;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.IMAGE_TYPE)) {
					typeImgResId = R.mipmap.empty_pic;
					try {
						iconPath = DirectoryUtil.genThumbnailFileFullName(
								context, mInfo.getOwnerBy(), mInfo.getId(), mInfo.getName());
						File thumBnail2 = new File(iconPath);
						if (!thumBnail2.exists()) {
							new ThumbnailAction().downloadThumbnailIcon(context, mInfo.getOwnerBy(),
									mInfo.getId(), iconPath, handler);
						} else {
							Message msg_download = new Message();
							msg_download.what = MessageCode.REQUEST_THUMBNAIL_INLOCAL;
							handler.sendMessage(msg_download);
						}
					} catch (Exception e) {
						e.printStackTrace();
						LogUtil.e(TAG,
								"[getTypeImgeID] fileType is image that show fail..."
										+ e.getLocalizedMessage());
					}
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.RAR_TYPE)) {
					typeImgResId = R.mipmap.rar;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.ZIP_TYPE)) {
					typeImgResId = R.mipmap.rar;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.VIDEO_TYPE)) {
					typeImgResId = R.mipmap.video;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.MUSIC_TYPE)) {
					typeImgResId = R.mipmap.music;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.TXT_TYPE)) {
					typeImgResId = R.mipmap.txt;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.PDF_TYPE)) {
					typeImgResId = R.mipmap.pdf;
				} else if (PublicTools.isFileType(mInfo.getName(),
						Constant.EXCEL_TYPE)) {
					typeImgResId = R.mipmap.excel;
				} else {
					typeImgResId = R.mipmap.default_file_icon;
				}
			} else {
				typeImgResId = R.mipmap.folder_im;
			}
			return typeImgResId;
		}

		ClientExceptionRelateHandler handler = new ClientExceptionRelateHandler() {
			
			@Override
			public Context getContext() {
				return context;
			}

			public void handleMessage(final Message msg) {
				switch(msg.what) {
				case MessageCode.REQUEST_THUMBNAIL_INLOCAL:
					new Thread(new Runnable() {
                        public void run() {
                        	LogUtil.i(TAG,"thumb path: " + iconPath);
                            Bitmap bmp = BitmapFactory.decodeFile(iconPath);
                            ShareDriveApplication.getInstance().addCloudBitmaps(bmp);
                            Message message = new Message();
                            message.what = UiConstant.UPDATE_TYPE_ICON;
                            message.obj = bmp;
                            handler.sendMessage(message);
                        }
                    }).start();
					break;
					
				case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
                    Bitmap bmp = (Bitmap) msg.obj;
                    if (null != bmp) {
                    	mItemIcon.setImageBitmap(bmp);
                    } else {
                        LogUtil.e(TAG, "bitmap is null, show default img...");
                    }
                    break;
                    
				default:
					super.handleMessage(msg);
				}
			}
		};
	}
	
}
